from typing import List,Union
import sys,os
#sys.path.append("C:\\Users\\Administrator\\Desktop\\VSCode\\IMS")
    
from fastapi import APIRouter,Depends,UploadFile,File
from fastapi.responses import FileResponse
# from fastapi.logger import logger

from tortoise import connections
from tortoise.transactions import atomic,in_transaction
from tortoise.exceptions import IntegrityError
from tortoise.expressions import Q
from tortoise.functions import Sum

from tortoise.contrib.pydantic import pydantic_queryset_creator

from models import Project,User,ProjectMembers,ProjectFiles,ProjectGroups,ProjectAuditRules,ProjectAuditRecords,ProjectBatches,ProjectLog
from scheams import (Project_Pydantic,ProjectIn_Pydantic
                     ,Response200,Response400
                     ,ProjectMembers_Pydantic,ProjectInWithId_Pydantic
                     ,ProjectMembersWithId_Pydantic
                     ,ProjectFiles_Pydantic,ProjectGroups_Pydantic
                     ,User_Pydantic,ProjectAuditRulesIn_Pydantic
                     ,ProjectAuditRules_Pydantic,ProjectAuditRecords_Pydantic
                     ,ProjectAuditRecordsIn_Pydantic,ProjectAuditRecordsAll_Pydantic
                     ,ProjectBatches_Pydantic,ProjectBatchesIn_Pydantic)
from core import deps,get_logger
from core.config import settings
from utils import getAuditRulesTotalPont

logger = get_logger(__name__)

project_batch = APIRouter(tags=["项目批次相关"],dependencies=[Depends(deps.get_current_user)])

@project_batch.post("/createBatch",summary="创建批次")
async def createBatch(batch: ProjectBatchesIn_Pydantic,user:User = Depends(deps.get_current_user)):
    
    # 权限判断 只有组长可以创建
    projectGroup = await ProjectGroups.filter(group_name=batch.group_name,group_member_id=user.username).first()
    
    if not projectGroup or projectGroup.group_member_role != settings.ProjectGroupMemberRole.LEADER:
        return Response400(msg="用户非组长，无法增加批次")
    
    
    if batch.group_name not in batch.batch_name:
        batch.batch_name = "-".join([batch.group_name,batch.batch_name])
        
    # IntegrityError
    try:
        res = await ProjectBatches.create(**batch.dict())
    except IntegrityError:
        return Response400(msg="批次名称重复")
        
    return Response200(data = await ProjectBatches_Pydantic.from_tortoise_orm(res))

@project_batch.post("/deleteBatch",summary="删除批次")
async def deleteBatch(id: int,user:User = Depends(deps.get_current_user)):
    
    projectBatch = await ProjectBatches.get(id=id)
    
    # 权限判断 只有组长可以创建
    projectGroup = await ProjectGroups.filter(group_name=projectBatch.group_name,group_member_id=user.username).first()
    
    if not projectGroup or projectGroup.group_member_role != settings.ProjectGroupMemberRole.LEADER:
        return Response400(msg="用户非组长，无法删除批次")
    
    projectCnt = await Project.filter(project_batch_id=projectBatch.batch_name).count()
    
    if projectCnt > 0 :
        return Response400(msg="该批次内已有项目，无法删除")
    
    await projectBatch.delete()
    
    return Response200(msg="删除成功")

@project_batch.post("/getBatches",summary="获取批次")
async def getBatches(group_name: settings.ProjectGroupName
                     ,limit: int = 10
                     ,page: int = 1):
    skip = (page - 1)*limit
    
    baseQuery = ProjectBatches.filter(group_name=group_name)
    
    cnt = await baseQuery.count()
    
    records = await ProjectBatches_Pydantic.from_queryset(baseQuery.order_by("-id").offset(skip).limit(limit))
    
    
    return Response200(data= {'cnt': cnt
                              ,'records': records })

@project_batch.get("/getProjectsByBatchName/{batch_name}",summary="根据批次获取项目列表")
async def getProjectsByBatchName(batch_name: str,limit: int = 10,page: int = 1):
    
    skip = (page - 1)*limit
    
    return Response200(data=await Project_Pydantic.from_queryset(Project.filter(project_batch_id=batch_name).offset(skip).limit(limit)))

@project_batch.post("/tag_batch",summary="将项目打上批次标签")
async def tag_batch(projects: List[int]
                    ,batch_name: str
                    ,group_name: settings.ProjectGroupName
                    ,user:User = Depends(deps.get_current_user)):
    
    projectGroup = await ProjectGroups.filter(group_name=group_name,group_member_id=user.username).first()
    
    if not projectGroup or projectGroup.group_member_role != settings.ProjectGroupMemberRole.LEADER:
        return Response400(msg="用户非组长，无法打批次标签")
    
    res = None
    
    async with in_transaction():
        res = await Project.select_for_update().filter(id__in=projects,statu=settings.ProjectStatus.SUBMITTED).update(project_batch_id=batch_name,statu=settings.ProjectStatus.PROFESSIONAL_AUDIT)
        
        bulk_list = []
        for id in projects:
            bulk_list.append(ProjectLog(project_id=id
                                        ,pre_statu=settings.ProjectStatus.SUBMITTED
                                        ,statu=settings.ProjectStatus.PROFESSIONAL_AUDIT
                                        ,user_id=user.username
                                        ,project_group=group_name))
        
        await ProjectLog.bulk_create(
            bulk_list
        )
    
    return Response200(data=res)

@project_batch.post("/getTaggingProjects",summary="获取待打标签项目组")
async def getTaggingProjects(project_group: settings.ProjectGroupName
                             ,limit: int = 10
                             ,page: int = 1
                             ,user:User = Depends(deps.get_current_user)):
    skip = (page - 1)*limit
    
    baseQuery = Project.filter(project_group=project_group,project_batch_id=None)
    
    cnt = await baseQuery.count()
    records = await Project_Pydantic.from_queryset(baseQuery.offset(skip).limit(limit))
    
    return Response200(data= {'cnt': cnt
                              ,'records': records})